<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-06-21 16:36:53
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-09-18 10:56:24
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\EquipManage\EquipType\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, reactive } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useDictStore } from '@/store/modules/dictData'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { TbIcContract } from '@/api/securcheck/type'
import Write from './components/write.vue'
import { Search } from '@/components/Search'
import SecurChecktbIcContractApi from '@/api/securcheck/ContractManage'
import DeptApi from '@/api/dept'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { createImageViewer } from '@/components/ImageViewer'
const { t } = useI18n()
const ids = ref<string[]>([])
const DictStore = useDictStore()
const userStore = useUserStore()
const PATH_URL = import.meta.env.VITE_API_PHOTO_PATH
//获取字典
DictStore.setDict('secur_contract_type') //厂商类型
DictStore.setDict('secur_contract_state')
//表格内容接口
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const i = await SecurChecktbIcContractApi.GettbIcContract({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = await SecurChecktbIcContractApi.DelettbIcContract(unref(ids)[0])
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const FormDisabled = ref(true)
//表格结构
const trackFile: any = ref([])
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    type: 'selection',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    fixed: 'left',
    search: { hidden: true }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    fixed: 'left',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'contractNo',
    label: t('合同编码'),
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '合同编码'
      }
    },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'unitName',
    label: t('单位名称'),
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'contractType',
    label: t('合同类型'),
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.secur_contract_type?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel)
        }
      })
    },
    form: {
      component: 'Select',
      colProps: {
        span: 12
      },
      componentProps: {
        options: DictStore.$state.secur_contract_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '合同类型',
        options: DictStore.$state.secur_contract_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'contractState',
    label: t('合同状态'),
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.secur_contract_state?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel)
        }
      })
    },
    form: {
      component: 'Select',
      colProps: {
        span: 12
      },
      componentProps: {
        options: DictStore.$state.secur_contract_state?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '合同状态',
        options: DictStore.$state.secur_contract_state?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'deptId',
    label: t('所属公司'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'TreeSelect',
      colProps: {
        span: 24
      },
      componentProps: {
        renderAfterExpand: false,
        showCheckbox: true,
        checkStrictly: true,
        checkOnClickNode: true,
        nodeKey: 'id',
        props: {
          label: 'label'
        }
      },
      optionApi: async () => {
        const res = await DeptApi.GetDeptListTree()
        return res.data
      }
    }
  },
  {
    field: 'signDate',
    label: t('签订时间'),
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      colProps: {
        span: 12
      },
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  },
  {
    field: 'endDate',
    label: t('到期时间'),
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 12
      },
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  },
  {
    field: 'remark',
    label: t('备注'),
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'file',
    label: '附件',
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Upload',
      componentProps: {
        action: '/api/file/upload',
        multiple: true,
        headers: { Authorization: userStore.getToken },
        beforeRemove: (uploadFile: any) => {
          return ElMessageBox.confirm(`确定要移除 ${uploadFile.name}?`).then(
            () => true,
            () => false
          )
        },
        onPreview: (file: any) => {
          // 判断是否为图片文件
          const isImage =
            file.type?.startsWith('image/') ||
            ['.jpg', '.jpeg', '.png', '.gif'].some((ext) => file.name?.toLowerCase().endsWith(ext))
          if (isImage) {
            // 图片文件 - 使用Element Plus的图片预览组件
            const imageUrl = file.response?.data?.url
              ? `${PATH_URL}${file.response.data.url}`
              : file.url
                ? `${PATH_URL}${file.url}`
                : null
            if (imageUrl) {
              createImageViewer({
                urlList: [imageUrl]
              })
            } else {
              ElMessage.warning('无法获取图片URL')
            }
          } else {
            const fileUrl = file.response?.data?.url
              ? `${PATH_URL}${file.response.data.url}`
              : file.url
                ? `${PATH_URL}${file.url}`
                : null

            if (fileUrl) {
              window.location.href = fileUrl
            } else {
              ElMessage.warning('无法获取文件URL')
            }
          }
        },
        onSuccess: (file: any) => {
          return file
        },
        slots: {
          default: () => <BaseButton type="primary">上传</BaseButton>
        }
      },
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'Edit')}>
                {t('修改')}
              </span>
              <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
                {t('查看')}
              </span>

              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const currentRow = ref<TbIcContract>()
const saveLoading = ref(false)
const delLoading = ref(false)
//表格删除操作
const delData = async (row: TbIcContract | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.uuid] : elTableExpose?.getSelectionRows().map((v: any) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const dialogVisible = ref(false)
const dialogTitle = ref('')
const MeterLedgerRef = ref()
const actionType = ref('')

const save = async () => {
  const write = unref(MeterLedgerRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await SecurChecktbIcContractApi.AddtbIcContract(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else if (actionType.value == 'Edit') {
      //修改字
      res.value = await SecurChecktbIcContractApi.EdittbIcContract(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
const ActionPublic = async (type: string, uuid: string | undefined) => {
  const res = await SecurChecktbIcContractApi.GettbIcContractById(uuid)
  dialogTitle.value = type == 'Edit' ? '修改' : '查看'
  FormDisabled.value = type == 'Edit' ? false : true
  if (res['file'] == null) {
    res['file'] = [] as any
  } else {
    if (!Array.isArray(res['file'])) {
      res['file'] = JSON.parse(res['file'])
    }
  }
  currentRow.value = res
}
//表格中操作
const action = async (row: TbIcContract, type: string) => {
  trackFile.value = []
  actionType.value = type
  dialogVisible.value = true //打开弹窗
  if (type == 'add') {
    dialogTitle.value = '新增'
    FormDisabled.value = false
    currentRow.value = {}
  } else if (type == 'Edit') {
    ActionPublic(type, row.uuid)
  } else {
    ActionPublic(type, row.uuid)
  }
}
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px" title="工商合同管理">
      <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="13" />新增
      </BaseButton>
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParams"
        @reset="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        row-key="uuid"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <Dialog v-model="dialogVisible" :title="dialogTitle" style="width: 800px">
      <Write
        ref="MeterLedgerRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :FormDisabled="FormDisabled"
      />
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped>
:deep(.el-radio-button--small .el-radio-button__inner) {
  padding: 7px 15px !important;
}
.el-tree-node:focus > .el-tree-node__content {
  color: #409eff;
}
.el-card__body {
  padding: 10px;
  /* height: 90%; */
}
.CloseBtn {
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
.el-collapse-item {
  padding: 15px 0;
}
.el-collapse-item__content {
  padding-bottom: 0;
}
.el-collapse-item__header {
  width: 62px;
  height: 24px;
  border-radius: 2px;
  color: white;
  background: #409eff;
  justify-content: center;
  font-size: 12px;
}
.el-collapse-item__arrow {
  margin: 0 2px;
}

:deep(.TableBtn) {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
